package com.hjy.websocketservice;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.server.WebSocketServer;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Component
public class WebSocketService extends WebSocketServer {


    private final List<WebSocket> clients = new ArrayList<>();
    private AtomicBoolean running = new AtomicBoolean(false);
    private static Boolean cease = false;
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public WebSocketService() {

        super(new InetSocketAddress(9393));
    }

    @Override
    public void onOpen(WebSocket conn, org.java_websocket.handshake.ClientHandshake handshake) {
        System.out.println("客户端连接成功");
        clients.add(conn); // 添加连接到客户端列表
        startVideoStream(conn);
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        clients.remove(conn); // 从客户端列表中移除连接
    }

    @Override
    public void onMessage(WebSocket conn, String message) {

        if ("start".equals(message)) {
            startVideoStream(conn);
        }
        if ("stop".equals(message)) {
        }
//        // 示例：给发送 "start" 消息的客户端发送回应
//        if ("custom".equals(message)) {
//            sendMessageToClient(conn, "Your custom response message");
//        }

    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        ex.printStackTrace();
    }

    @Override
    public void onStart() {
        System.out.println("WebSocket 服务器启动成功");
    }

    private void startVideoStream(WebSocket conn) {
        if (conn.isOpen()) {
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
    }




    /**
     * 向特定的客户端发送消息：
     *
     * @param client
     * @param webSocketResponse
     */
    public void sendMessageToClient(WebSocket client, WebSocketResponse webSocketResponse) {

        if (client != null && client.isOpen()) {
            client.send(webSocketResponse.toString());
        }
    }

    /**
     * 广播到所有连接的客户端
     *
     * @param message
     */
    public void broadcastMessage(String message) {
        for (WebSocket client : clients) {
            if (client.isOpen()) {
                client.send(message);
            }
        }
    }


}
